const userModel = require('../model/userModel');
let axios = require('axios')
const SECRET = 'ewgfvwergvwsgw5454gsrgvsvsd'
const jwt = require('jsonwebtoken')


const userController = {
    login(req, res) {
        let userInfo={}
        axios.get(`https://api.weixin.qq.com/sns/jscode2session?appid=wx7f9bdf9647d14cb1&secret=ea201a1a1d3b477275dac28748b4fcf0&js_code=${req.query.js_code}&grant_type=authorization_code`).then(value => {
            axios.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx7f9bdf9647d14cb1&secret=ea201a1a1d3b477275dac28748b4fcf0').then(ress => {
                userInfo.openid=value.data.openid
                userInfo.access_token=ress.data.access_token
                userModel.getUserInfo(userInfo, (err, result) => {
                    let response = {
                        code: 0,
                        msg: ''
                    }
                    if (err) {
                        response.code = 500;
                        response.msg = '服务器发生了错误';
                    } else {
                        response.data = result
                        response.token = jwt.sign({id: String(result._id)}, SECRET)
                    }
                    res.json(response);
                })
            })
        })
    },
    userInfo(req, res) {
        let userInfo={
            avatarUrl:req.body.avatarUrl||'',
            city:req.body.city||'',
            gender:req.body.gender||'',
            nickName:req.body.nickName||'',
            id:req.id
        }
        userModel.userInfo(userInfo,(err,result)=>{
            let response = {
                code: 0,
                msg: ''
            }
            res.json(response);
        })
    }
}
module.exports = userController;